package com.qingke.learn.mybatis.ch02;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.qingke.learn.mybatis.pojo.Student;

public class MybatisIfTest {
	
	public static void main(String[] args) {
		//ifTest();
		chooseTest();
	}
	
	public static void ifTest()	{
		SqlSession session = creatSqlSession();
		String stmt = "com.qingke.learn.mybatis.mapping.studentMapping.getStudentLikeName";		
		Student student = new Student();
		
		System.out.println("student is null:");
		List<Student> list = session.selectList(stmt, student);
		for (Student s : list) {
			System.out.println(s);
		}
		
		System.out.println("\nstudent name is empty:");
		student.setName("");
		List<Student> list2 = session.selectList(stmt, student);
		for (Student s : list2) {
			System.out.println(s);
		}
		
		System.out.println("\nstudent name is contain 2:");
		student.setName("2");
		List<Student> list3 = session.selectList(stmt, student);
		for (Student s : list3) {
			System.out.println(s);
		}
		
		close(session);
	}
	
	public static void chooseTest() {
		SqlSession session = creatSqlSession();
		String stmt = "com.qingke.learn.mybatis.mapping.studentMapping.usechoose";		
		Student student = new Student();
		
		System.out.println("student is null:");
		List<Student> list = session.selectList(stmt, student);
		for (Student s : list) {
			System.out.println(s);
		}
		
		System.out.println("\nstudent name is empty:");
		student.setName("");
		List<Student> list2 = session.selectList(stmt, student);
		for (Student s : list2) {
			System.out.println(s);
		}
		
		System.out.println("\nstudent name is contain 2:");
		student.setName("2");
		List<Student> list3 = session.selectList(stmt, student);
		for (Student s : list3) {
			System.out.println(s);
		}
		
		close(session);
		}
	
	public static SqlSession creatSqlSession() {
		
		InputStream is = MybatisIfTest.class.getClassLoader().getResourceAsStream("mybatis.conf.xml");
		
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
		
		SqlSession session = sessionFactory.openSession();
		
		try {
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return session;
	}
	
	public static void close(SqlSession session) {
		session.close();
	}
}
